# -*-coding:utf-8 -*-

import os,re,traceback
import pickle
import time
import requests
try:
    from ..config import ROOT_PATH,COOKIE_NAME,HTTP_HEADER
except :
    from config import ROOT_PATH,COOKIE_NAME,HTTP_HEADER

import logging
log= logging.getLogger(__name__)  #没用暂时

from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def get(url, _header, charset,_param=None):
    try:
        start = int(time.time())
        log.info(u'开始请求:%s' % url)
        if _param == None:
            response = requests.get(url, headers=_header,verify=False, timeout=10)
        else:
            response = requests.get(url, headers=_header,params=_param,verify=False,timeout=10)
        response.encoding = charset
        log.info(u'get requests cost %s s' % (int(time.time()) - start))
        #return response.content
        return response.text
    except Exception as e:
        log.error(e)
        log.error(u'get-->%s 获取失败' % url)
        return None
        #return get(url, _header,charset,cookie,_param)

def post(url, _header,_data, charset):
    try:
        start = int(time.time())
        log.info(u'开始请求:%s' % url)
        response = requests.post(url, headers=_header,data=_data,verify=False,timeout=5)
        response.encoding = charset
        log.info(u'post requests cost %s s' % (int(time.time()) - start))
        #print (response)
        #return response.content
        return response.text,response.status_code
    except Exception as e:
        log.error(e)
        print(traceback.print_exc())
        log.error(u'post-->%s 获取失败' % url)
        return None
        #return 'error',0
        #return post(url, _header,_data,charset,cookie)

'''
处理重定向问题
'''
def redirect_get(url,_header,_relogin_url):
    try:
        log.info(u'开始请求:%s' % url)
        response = requests.get(url, headers=_header,allow_redirects=False)
        if response.status_code == 302:
            str_location_url = response.headers["Location"]
            #print response.headers
            if str_location_url == _relogin_url:
                log.error(u'--> 需要重新登陆')
                return False
            return redirect_get(str_location_url,_header,_relogin_url)
        elif response.status_code == 200:
            #print (response.headers)
            #response.encoding = "utf-8"
            return response
        else:
            log.error(u'-->%s 获取失败,status_code=%d' % (url,response.status_code))
            return ""
    except requests.exceptions.Timeout as e:
        log.error(u'-->%s 获取超时' % url)
        return redirect_get(url, _header,_relogin_url)
    except Exception as e:
        log.error(e)
        log.error(u'-->%s 获取失败' % url)
        return False


'''
带cookie获取请求下载  重定向问题
'''
def cookie_redirect_get(url,_relogin_url,success_header):
    try:
        with open(COOKIE_NAME,"r") as f:
            cookie_dict = pickle.load(f)
            str_cookie = ""
            for item in cookie_dict.keys():
                str_cookie = str_cookie +item + "=" + cookie_dict[item] + "; "
            #print str_cookie
            HTTP_HEADER["Cookie"] = str_cookie
            res = redirect_get(url,HTTP_HEADER,_relogin_url)
            print (res.headers)
            if res.status_code == 200:
                if str(res.headers).find(success_header) != -1:
                    return res
                else:
                    #time.sleep(2)
                    #return cookie_get(url,success_header)
                    log.error(u'-->%s 获取失败' % url)
                    return False
            
    except requests.exceptions.Timeout as e:
        log.error(u'-->%s 获取超时' % url)
        return cookie_redirect_get(url,_relogin_url,success_header)
    except Exception as e:
        log.error(e)
        log.error(u'-->%s 获取失败' % url)
        return False
        

'''
直接带cookie获取请求下载
'''
def cookie_get(url,success_header):
    try:
        with open(COOKIE_NAME,"r") as f:
            cookie_dict = pickle.load(f)
            log.info(u'开始请求:%s' % url)
            cook =  requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)
            res = requests.get(url,headers = HTTP_HEADER,cookies=cook)
            if res.status_code == 200:
                if str(res.headers).find(success_header) != -1:
                    return res.content
                else:
                    #time.sleep(2)
                    #return cookie_get(url,success_header)
                    log.error(u'-->%s 获取失败' % url)
                    return False
            
    except requests.exceptions.Timeout as e:
        log.error(u'-->%s 获取超时' % url)
        return cookie_get(url,success_header)
    except Exception as e:
        log.error(e)
        log.error(u'-->%s 获取失败' % url)
        return False
        
